package com.java复习.反射1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 解析xml文件
        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read("resources\\demo1.xml");

        // 获取根元素
        Element rootElement = document.getRootElement();

        // 通过根元素，来获取子元素的集合
        List<Element> beanList = rootElement.elements("bean");

        Element pigElement = beanList.get(1);

        String id = pigElement.attributeValue("id");
        String className = pigElement.attributeValue("className");

        Class clazz = Class.forName(className);

        // 创建一个小猪对象
        Object obj = clazz.newInstance();

        // 个小猪对象赋值，名字，年龄
        // 1、获取属性值
        List<Element> proList = pigElement.elements("pro");

        for (Element pro:proList){
            String name = pro.attributeValue("name");
            String val = pro.attributeValue("val");

            Field tem_field = clazz.getDeclaredField(name);
            tem_field.setAccessible(true);
            if(name.equals("age")){
                int age = Integer.parseInt(val);
                tem_field.set(obj,age);
            }else {
                tem_field.set(obj,val);
            }

        }

        System.out.println(obj);
    }
}
